package com.baizhi.service.impl;

import com.baizhi.annotation.AddCacheAnnotation;
import com.baizhi.annotation.LogAnnotion;
import com.baizhi.dao.BzMenuMapper;
import com.baizhi.entity.BzMenu;
import com.baizhi.service.IBzMenuService;
import com.baizhi.vo.MenuVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单管理 服务实现类
 * </p>
 *
 * @author xhc
 * @since 2020-09-24
 */
@Service
public class BzMenuServiceImpl extends ServiceImpl<BzMenuMapper, BzMenu> implements IBzMenuService {


    @Resource
    private   BzMenuMapper  menuMapper;

    @Override
    public List<BzMenu> selectMenus() {
     return menuMapper.selectMenus();
    }

    @Override
//    @LogAnnotion(type = "",content = "")
    @AddCacheAnnotation
    public List<MenuVo> selectMenusByStream() {

        List<BzMenu> bzMenus = menuMapper.selectList(null);

        /**
         *  三级联查通过stream实现
         * 1 先找的所有的一级菜单
         * 2 根据一级菜单找到所有的二级惨淡
         * 3 根据二级菜单找到所有的三级菜单
         *
         */
        List<MenuVo> menuVoList = bzMenus.stream().filter(bzMenu ->
                bzMenu.getParentId() == 0)
                .map(bzMenu -> {
//                    对象转化   bzmenu-----vo
                    MenuVo menuVo = new MenuVo();
                    BeanUtils.copyProperties(bzMenu, menuVo);
                    menuVo.setMenuList(getMenuList(menuVo, bzMenus));
                    return menuVo;
                }).collect(Collectors.toList());

        return menuVoList;

    }

    private List<MenuVo> getMenuList(MenuVo menuVo, List<BzMenu> bzMenus) {
        /**
         *
         * 根据bzmenu在在集合中找到下一级
         */
        List<MenuVo> Vos = bzMenus.stream().filter(bzMenu -> {
            return bzMenu.getParentId() == menuVo.getMenuId();
        }).map(bzMenu -> {
//            对象转化   bzmenu-----vo
            MenuVo menuVo1 = new MenuVo();
            BeanUtils.copyProperties(bzMenu, menuVo1);
            menuVo1.setMenuList(getMenuList(menuVo1, bzMenus));
            return menuVo1;
        }).collect(Collectors.toList());

        return Vos;
    }

}
